//引入模块
const express = require("express");
require('express-async-errors')
//引入上一级目录下的mysql的Query对象
const query = require("../util/query.js");
const {md5} = require('../util/md5.js');
const Token = require('../util/token.js');
const response = require("./response");


function success(msg, data) {
    return {code: 1, msg: msg, data: data, state: true}
}

function exp(code, msg) {
    return {code: code, msg: msg, data: {}, state: false}
}

function fail(msg) {
    return {code: 500, msg: msg, data: {}, state: false}
}


//创建空路由器
let router = express.Router();
//挂载路由
//===============================================
//验证用户是否已经登录接口  Session验证
router.get("/islogin_session", (req, res) => {
    //获取请求的数据
    //验证数据
    //如果session中有用户数据，则表明已经登录
    let user = req.session.user;
    if (user) {
        delete user.password;
        let session_id = req.session.id;
        res.send({code: 1, msg: "已登录", data: {user, session_id}});
    } else {
        res.send({code: 2, msg: "没有登录", data: {}});
    }
});

//===============================================
//2.登录用户 POST /login_session  session登录验证
router.post("/login_session", async (req, res) => {
    try {
        //1.1获取数据
        let userLogin = req.body;
        //1.2验证各项数据是否为空
        if (!userLogin.name) throw "用户名不能为空";
        if (!userLogin.password) throw "密码不能为空";

        //执行SQL语句,查看是否是否有这样的用户
        let sql = `SELECT id,name,password,salt FROM user WHERE name ="${userLogin.name}"`; //"
        console.log(sql);

        let result = await query(sql);
        //console.log(result[0]);
        //判断查询的结果（数组）长度是否大于0,如果大于0，说明查询到数据，有这个用户
        if (result.length > 0) {
            let user = result[0];
            if (user.password === md5(userLogin.password + user.salt)) {
                //密码正确,登陆成功后
                delete user.password;
                delete user.salt;
                req.session.user = user; //将用户name和id保存在session中
                let session_id = req.session.id;
                res.send({code: 1, msg: "登录成功", data: {user, session_id}});
                return;
            }
        } else throw "用户名或密码错误";
    } catch (error) {
        res.send({code: -1, msg: "Query异常,error:" + error});
    }
});

//2.登录用户 POST /login  token登录验证
router.post('/login', async (req, res) => {
    try {
        //1.1获取数据
        let userLogin = req.body;
        //1.2验证各项数据是否为空
        if (!userLogin.account) throw "用户名不能为空";
        if (!userLogin.password) throw "密码不能为空";

        //执行SQL语句,查看是否是否有这样的用户
        let sql = `SELECT id,name,password,salt,type FROM user WHERE name ="${userLogin.account}"`;

        let result = await query(sql);
        //判断查询的结果（数组）长度是否大于0,如果大于0，说明查询到数据，有这个用户
        if (result.length > 0) {
            let user = result[0];
            if (user.password === md5(userLogin.password + user.salt)) {
                //密码正确,登陆成功后
                delete user.password;
                delete user.salt;
                //生成Token
                //设置Token携带的信息

                //jwt--jsonwebtoken第三方库生成Token
                let token = Token.sign(JSON.parse(JSON.stringify(user)));
                res.send(success("登录成功", {user, token}));
                return;
            }
        }
        res.status(401).send(exp(401, "用户名或密码错误"))

    } catch (error) {
        res.send(fail(error));
    }
});

//验证用户是否已经登录接口 Token验证
router.get("/islogin", (req, res) => {
    const token = req.headers.authorization // 取到请求头中Token

    let result = Token.verify(token);
    if (result.code == 1) {
        let user = result.data;
        res.send({code: 1, msg: "已登录", data: {user, token}, state: true});
    } else {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {},
            state: false
        });
    }
});


router.get('/token/renew', (req, res) => { //
    const token = req.headers.authorization // 取到请求头中Token

    let result = Token.verify(token);
    if (result.code == 1) {
        let user = result.data;
        // 重新生成一个新的Token, 返回给前端
        // 设置Token携带的信息
        let payload = {
            userId: user.id,
            userName: user.name
        };
        let token = Token.sign(payload);
        res.send({
            code: 1,
            msg: '成功',
            data: {
                user,
                token,
            }
        });
    } else {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
    }
})


//===============================================
//用户注册
router.post("/register", async (req, res) => {
    //console.log( req.body );//调试输出
    //1.1获取post请求的数据
    let user = req.body;
    //1.2验证各项数据是否为空
    try {
        if (!user.name) throw "用户名不能为空";
        if (!user.password) throw "密码不能为空";
        if (!user.email) throw "邮箱不能为空";

        //生成盐（作料）,密码MD5加密
        user.remark = user.password; //方便调试，密码明码暂放在备注字段
        user.salt = md5(Date.now().toString()); //生成盐（作料）
        user.password = md5(user.password + user.salt); //密码=MD5(明码+盐)

        //1.3执行SQL语句,将注册的数据插入到user数据表中
        let sql = "INSERT INTO user SET ?";
        let result = await query(sql, [user]);
        if (result.affectedRows > 0) {
            let data = {user: {id: result.insertId, name: user.name}};
            res.send({code: 1, msg: "注册成功", data});
        } else {
            throw result;
        }
    } catch (error) {
        res.send({code: -1, msg: `注册失败, 错误信息: ${error}`});
    }
});

//===============================================
//退出登录 GET /logout
router.get("/logout", (req, res) => {
    // req.session.destroy();
    res.send({code: 1, msg: "登出成功", state: true});
});


//以下待完成........................

//3.检索用户 GET /detail
router.get("/detail", (req, res) => {
    //1.1获取get请求的数据
    let user = req.query;
    //1.2验证各项数据是否为空
    if (!user.uid) {
        res.send({code: 401, msg: "uid required"});
        return;
    }

    //1.3执行SQL语句
    let sql = "SELECT uid,uname,email,phone FROM xz_user WHERE uid=?";
    pool.query(sql, [user.uid], (err, result) => {
        if (err) throw err;

        //如果数据查询成功，响应对象
        if (result.length > 0) {
            res.send({
                code: 200,
                msg: "ok",
                data: result[0],
            });
        } else {
            res.send({
                code: 301,
                msg: "can not found",
                data: {},
            });
        }
    });
});
//===============================================
//4.修改用户 POST /update
router.post("/update", (req, res) => {
    //console.log( req.body );
    //1.1获取数据
    let user = req.body;
    //1.2验证各项数据是否为空
    let codeno = 400;
    for (const key in user) {
        codeno++;
        if (!user[key]) {
            res.send({code: codeno, msg: `${key} required`});
            return;
        }
    }

    //1.3执行SQL语句 ，修改用户表中对应的数据
    let sql = "UPDATE xz_user SET ? WHERE uid=?";
    pool.query(sql, [user, user.uid], (err, result) => {
        if (err)
            res.send({
                code: 201,
                msg: `update failed, err: ${err}`,
            }); //throw err;

        //如果数据更改成功，响应对象
        if (result.affectedRows > 0) {
            res.send({
                code: 200,
                msg: "update success",
                data: user,
            });
        } else {
            res.send({
                code: 301,
                msg: "update error",
                data: user,
            });
        }
    });
});
//===============================================
//5.用户列表 GET /list
router.get("/list", (req, res) => {
    console.log(req.query);
    //1.1获取数据
    //1.2如果页码pno为空 默认为1 如果pageSize大小为空默认是2  要保证pageSize大小为整数
    //处理页码
    let pno = parseInt(req.query.pno);
    pno = pno ? pno : 1;
    //处理每页大小
    let pageSize = parseInt(req.query.pageSize);
    pageSize = pageSize ? pageSize : 2;
    //
    // 4计算开始查询的值start
    let start = (pno - 1) * pageSize;

    //1.3执行2个SQL语句
    let sql =
        "SELECT count(*) as Count FROM xz_user; SELECT * FROM xz_user ORDER BY uid DESC LIMIT ?,? ";
    pool.query(sql, [start, pageSize], (err, result) => {
        if (err)
            res.send({
                code: 301,
                msg: `list failed, err: ${err}`,
            }); //throw err;

        let count = result[0][0]["Count"]; //获取记录总数，第1个SQL执行结果
        let pageCount = Math.floor(count / pageSize) + 1; //计算总页数
        //如果数据获取成功（记录数量是0也是一种成功），响应对象
        res.send({
            code: 200,
            msg: "list ok",
            recordCount: result[1].length, //第2个SQL执行结果的行数
            pageSize: pageSize, //每页大小
            pageCount: pageCount, //总页数
            data: result[1], //第2个SQL执行结果
        });
    });
});

//===============================================
//6.删除用户 GET /delete
router.get("/delete", (req, res) => {
    console.log(req.query);
    //1.1获取数据
    let user = req.query;
    //1.2验证数据
    if (!user.uid) {
        res.send({code: 401, msg: "uid required"});
        return;
    }
    //1.3执行SQL语句，删除对应的数据
    let sql = "DELETE FROM xz_user WHERE uid =?";
    pool.query(sql, [user.uid], (err, result) => {
        if (err)
            res.send({
                code: 301,
                msg: `delete failed, err: ${err}`,
            }); //throw err;

        console.log(result);
        //数据库操作影响的记录行数，判断是否删除成功
        if (result.affectedRows > 0) {
            res.send({
                code: 200,
                msg: `delete success ：uid=${user.uid}`,
            });
        } else {
            res.send({
                code: 301,
                msg: `delete error ： uid=${user.uid}`,
            });
        }
    });
});

//===============================================
//7.检测邮箱 (是否存在这样的邮箱）GET /checkemail
router.get("/checkemail", (req, res) => {
    console.log(req.query);
    //1.1获取数据
    let user = req.query;
    //1.2验证数据
    if (!user.email) {
        res.send({code: 401, msg: "email required"});
        return;
    }
    //1.3执行SQL语句
    let sql = "SELECT 1 FROM xz_user WHERE email =?";
    pool.query(sql, [user.email], (err, result) => {
        if (err) {
            res.send({code: 301, msg: `select failed, err: ${err}`}); //throw err;
            return;
        }

        //数据库操作影响的记录行数
        if (result.length > 0) {
            res.send({
                code: 201,
                msg: `email exists  email=${user.email}`,
            });
        } else {
            res.send({
                code: 200,
                msg: `checkemail ok email=${user.email}`,
            });
        }
    });
});

//===============================================
//8.检测手机 (是否存在这样的手机）GET /checkphone
router.get("/checkphone", (req, res) => {
    console.log(req.query);
    //1.1获取数据
    let user = req.query;
    //1.2验证数据
    if (!user.phone) {
        res.send({code: 401, msg: "phone required"});
        return;
    }
    //1.3执行SQL语句
    let sql = "SELECT 1 FROM xz_user WHERE phone =?";
    pool.query(sql, [user.phone], (err, result) => {
        if (err) {
            res.send({code: 301, msg: `select failed, err: ${err}`}); //throw err;
            return;
        }

        //数据库操作影响的记录行数
        if (result.length > 0) {
            res.send({
                code: 201,
                msg: `phone exists  phone=${user.phone}`,
            });
        } else {
            res.send({
                code: 200,
                msg: `checkphone ok phone=${user.phone}`,
            });
        }
    });
});

//===============================================
//9.检测用户名 (是否存在这样的用户名）GET /checkuname
router.get("/checkuname", (req, res) => {
    console.log(req.query);
    //1.1获取数据
    let user = req.query;
    //1.2验证数据
    if (!user.uname) {
        res.send({code: 401, msg: "uname required"});
        return;
    }
    //1.3执行SQL语句
    let sql = "SELECT 1 FROM xz_user WHERE uname =?";
    pool.query(sql, [user.uname], (err, result) => {
        if (err) {
            // throw err;
            res.send({code: 301, msg: `select failed, errMessage: ${err}`});
            return;
        }
        //console.log(result);
        //数据库操作影响的记录行数
        if (result.length > 0) {
            res.send({
                code: 201,
                msg: `uname exists  phone=${user.uname}`,
            });
        } else {
            res.send({
                code: 200,
                msg: `checkuname ok uname=${user.uname}`,
            });
        }
    });
});

//===============================================
//11.获取当前用户信息接口 GET /sessiondata
router.get("/sessiondata", (req, res) => {
    res.send({
        code: 200,
        msg: "success",
        data: {
            uid: req.session.loginUid,
            uname: req.session.loginUname,
        },
    });
});

//12.检索用户 GET /info
router.get("/info", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let uid = data.data.id
    //1.3执行SQL语句
    let sql = `SELECT id,name,email,phone,sex,age FROM user WHERE id=${uid} limit 1`;
    query(sql).then(result => {
        res.send(response.success(result[0]))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
});

//13.检索用户 Post /info
router.post("/info", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let body = req.body;
    delete body.id
    let id = data.data.id
    //1.3执行SQL语句
    let sql = `update user set ? WHERE id=${id} limit 1`;
    query(sql, body).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
});

//14.获取钱包信息 get /wallet
router.get("/wallet", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);

    let id = data.data.id
    //1.3执行SQL语句
    let sql = `select id,money,card_no from user WHERE id=${id} limit 1`;
    query(sql).then(result => {
        res.send(response.success(result[0]))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
});

//15.获取钱包信息 post /onCashIn
router.post("/onCashIn", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);

    let id = data.data.id
    //1.3执行SQL语句
    let addMoney = req.body.change_money;
    if (addMoney < 0) {
        return res.send(response.fail("充值金额错误!"))
    }

    let sql = `update user set money=(IFNULL(money,0)+${addMoney}) WHERE id=${id}`;
    query(sql).then(result => {
        res.send(response.success(result[0]))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
});

//15.获取钱包信息 post /onCashOut
router.post("/onCashOut", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);

    let id = data.data.id
    //1.3执行SQL语句
    let change_money = req.body.change_money;
    if (change_money < 0) {
        return res.send(response.fail("金额错误!"))
    }

    let sql = `update user set money=(IFNULL(money,0)-${change_money}) WHERE id=${id}`;
    query(sql).then(result => {
        res.send(response.success(result[0]))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
});

// error handle
router.use((err, req, res, next) => {
    if (req.xhr) {
        return res.json({
            code: 500,
            state: false,
            msg: err.message
        });
    }
    next(err);
});
//===============================================
//导出路由器
module.exports = router;
